package com.ddstation.common.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONObject;

public class HttpClientUtil {
	
	/**
	 * Post请求
	 * @param url
	 * @param params
	 * @param connectTimeout
	 * @param socketTimeout
	 * @return
	 */
	public static JSONObject post(String url, Map<String, String> params, int connectTimeout, int socketTimeout) {
		HttpPost httppost = null;
        try {
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            httppost = new HttpPost(url);
            if(connectTimeout > 0 && socketTimeout > 0){
				//设置请求和传输超时时间
				RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
				httppost.setConfig(requestConfig);
			}
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            if (params != null && !params.isEmpty()) {
            	for (String key : params.keySet()) {
            		nameValuePairs.add(new BasicNameValuePair(key, params.get(key)));
				}
            }
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "utf-8"));
            CloseableHttpResponse response = httpclient.execute(httppost);
            if (response == null || response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            	if (logger.isDebugEnabled()) {
            		logger.debug("消息发送成功");
            	}
            	String jsonString = EntityUtils.toString(response.getEntity());
				return JSONObject.fromObject(jsonString);
            } else {
            	logger.error("消息发送失败");
            	if (response != null) {
            		logger.error("statusCode：" + response.getStatusLine().getStatusCode());
            	}
            	return null;
            }

        } catch(Exception e) {
            throw new RuntimeException(e);
        } finally {
            if(httppost != null)
                httppost.releaseConnection();
        }
	}


	/**
	 * 发送post请求
	 * @param json
	 * @param URL
	 * @return
	 */
	public static JSONObject sendPost(JSONObject json,String URL) {
		CloseableHttpClient client = HttpClients.createDefault();
		HttpPost post = new HttpPost(URL);
		post.setHeader("Content-Type", "application/json");
		post.addHeader("Authorization", "Basic YWRtaW46");
		String result;
		try {
			StringEntity s = new StringEntity(json.toString(), "utf-8");
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
					"application/json"));
			post.setEntity(s);
			// 发送请求
			HttpResponse httpResponse = client.execute(post);
			// 获取响应输入流
			InputStream inStream = httpResponse.getEntity().getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					inStream, "utf-8"));
			StringBuilder strber = new StringBuilder();
			String line;
			while ((line = reader.readLine()) != null)
				strber.append(line + "\n");
			inStream.close();
			result = strber.toString();
			if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				System.out.println("请求服务器成功，做相应处理");
			} else {
				System.out.println("请求服务端失败");
			}
		} catch (Exception e) {
			logger.error("请求异常："+e.getMessage());
			throw new RuntimeException(e);
		}
		return JSONObject.fromObject(result);
	}


	/**
	 * 发送post请求
	 * @param tableName
	 * @param dataList
	 * @param accessUrl
	 * @return
	 */
	public static JSONObject sendPost2(String tableName,List<Map<String, Object>> dataList,String accessUrl) {
		String result = null;
		// 获得Http客户端(可以理解为:你得先有一个浏览器;注意:实际上HttpClient与浏览器是不一样的)
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		// 创建Post请求
		URI uri = null;
		try {
			// 将参数放入键值对类NameValuePair中,再放入集合中
			List<NameValuePair> params = new ArrayList<>();
			params.add(new BasicNameValuePair("tableName", tableName));
			// 设置uri信息,并将参数集合放入uri;
			// 注:这里也支持一个键值对一个键值对地往里面放setParameter(String key, String value)
			uri = new URIBuilder(accessUrl).setParameters(params).build();
		} catch (URISyntaxException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
		HttpPost httpPost = new HttpPost(uri);
		// 将对象转换为json字符串，并放入entity中
		StringEntity entity = new StringEntity(com.alibaba.fastjson.JSONObject.toJSONString(dataList), "UTF-8");
		// post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
		httpPost.setEntity(entity);
		httpPost.setHeader("Content-Type", "application/json;charset=utf8");

		// 响应模型
		CloseableHttpResponse response = null;
		try {
			// 由客户端执行(发送)Post请求
			response = httpClient.execute(httpPost);
			// 从响应模型中获取响应实体
			HttpEntity responseEntity = response.getEntity();
			result = EntityUtils.toString(responseEntity);

			if (responseEntity != null) {
				System.out.println("响应内容长度为:" + responseEntity.getContentLength());
				System.out.println("响应内容为:" + result);
			}
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				// 释放资源
				if (httpClient != null) {
					httpClient.close();
				}
				if (response != null) {
					response.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result==null?null:JSONObject.fromObject(result);
	}



	private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
}
